import {reqGetCode,reqUserRegister,reqUserLogin,reqGetUserInfo,reqLogout} from '@/api'
import { setToken, getToken, removeToken } from '@/utils/token'
//登录和注册的仓库
const state = {
    code: '',
    // token:'',
    token: getToken(),
    userInfo: {}
}
const mutations = {
    GETCODE(state,code){
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
      },
    GETUSERINFO(state, userInfo) {
      state.userInfo = userInfo
    },
    CLEAR(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
}
const actions = {
    //获取验证码
    async getCode({commit},phone){
        let result  =  await reqGetCode(phone);
        if(result.code == 200){
            commit("GETCODE",result.data);
            return 'ok'
        }else{
            return Promise.reject(new Error(result.message));
        }
    },
    //用户注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        if (result.code === 200) {
          return 'OK'
        } else {
          return Promise.reject(new Error(result.message))
        }
      },
    //用户登录 token
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        if (result.code == 200) {
          commit('USERLOGIN', result.data.token)
          //持久化存储taken         
          setToken(result.data.token)
          return 'OK'
        } else {
          return Promise.reject(new Error(result.message))
        }
      },
    //获取用户信息
    async getUserInfo({ commit }) {
      let result = await reqGetUserInfo()
      console.log(result)
      if (result.code === 200) {
        commit('GETUSERINFO', result.data)
        return 'OK'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录
    async userLogout({ commit }) {
      let result = await reqLogout()
      if (result.code === 200) {
        commit('CLEAR')
        return 'OK'
      } else {
        return Promise.reject(new Error(result.message))
      }
    }
}
const getters = {}
export default({
    state,//数据存放
    mutations,//修改state数据
    actions,//业务逻辑
    getters,//计算属性
   
})